<template>
  <div class="weekly-stats-container">
    <div class="stats-header">
      <h3>周报统计</h3>
      <div class="period-selector">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          @change="fetchWeeklyStats"
        />
        <el-button type="primary" @click="exportStats">导出统计</el-button>
      </div>
    </div>

    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(stat, index) in overviewStats" :key="index">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-icon">
              <el-icon>
                <component :is="stat.icon"></component>
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="stats-charts">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>工作时长趋势</span>
                <el-radio-group v-model="workTrendType" size="small" @change="updateWorkTrendChart">
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="workTrendChart"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>任务完成情况</span>
              </div>
            </template>
            <div class="chart-container" ref="taskCompletionChart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="weekly-records">
      <el-card shadow="hover">
        <template #header>
          <div class="records-header">
            <span>历史周报记录</span>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索周报内容"
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </template>
        
        <el-table
          :data="filteredWeeklyRecords"
          style="width: 100%"
          border
          v-loading="loading"
        >
          <el-table-column prop="week" label="周数" width="120" sortable />
          <el-table-column prop="dateRange" label="日期范围" width="220" sortable />
          <el-table-column prop="workHours" label="工作时长(h)" width="120" sortable />
          <el-table-column prop="taskCount" label="任务数" width="100" sortable />
          <el-table-column prop="completionRate" label="完成率" width="120" sortable>
            <template #default="scope">
              <el-progress
                :percentage="scope.row.completionRate"
                :status="scope.row.completionRate === 100 ? 'success' : ''"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="viewWeeklyDetail(scope.row)"
              >
                查看
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteWeekly(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalRecords"
            layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 周报详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="周报详情"
      width="60%"
    >
      <div class="weekly-detail" v-if="currentWeekly">
        <h4>{{ currentWeekly.week }} ({{ currentWeekly.dateRange }})</h4>
        
        <div class="detail-section">
          <h5>本周工作总结</h5>
          <ul class="task-list">
            <li class="task-item" v-for="(task, index) in currentWeekly.tasks" :key="index">
              <div class="task-title">
                <el-tag :type="task.completed ? 'success' : 'warning'" size="small">
                  {{ task.completed ? '已完成' : '进行中' }}
                </el-tag>
                <span>{{ task.title }}</span>
              </div>
              <div class="task-desc">{{ task.description }}</div>
              <div class="task-meta">
                <span>工时: {{ task.hours }}小时</span>
                <span>优先级: {{ getPriorityText(task.priority) }}</span>
              </div>
            </li>
          </ul>
        </div>
        
        <div class="detail-section">
          <h5>下周工作计划</h5>
          <ul class="plan-list">
            <li v-for="(plan, index) in currentWeekly.plans" :key="index">
              {{ plan }}
            </li>
          </ul>
        </div>
        
        <div class="detail-section">
          <h5>问题与建议</h5>
          <p>{{ currentWeekly.issues || '无' }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { Search, Calendar, Watch, Document, CircleCheck } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { 
  TitleComponent, TooltipComponent, GridComponent, 
  LegendComponent, ToolboxComponent 
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的 echarts 组件
echarts.use([
  TitleComponent, TooltipComponent, GridComponent, LegendComponent,
  ToolboxComponent, BarChart, LineChart, PieChart, CanvasRenderer
])

// 数据状态
const dateRange = ref([new Date(new Date().getFullYear(), new Date().getMonth(), 1), new Date()])
const workTrendType = ref('week')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentWeekly = ref(null)

// 图表引用
const workTrendChart = ref(null)
const taskCompletionChart = ref(null)
let workTrendChartInstance = null
let taskCompletionChartInstance = null

// 时间选择快捷方式
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 概览数据
const overviewStats = ref([
  {
    icon: 'Calendar',
    label: '周报总数',
    value: 12
  },
  {
    icon: 'Watch',
    label: '总工时',
    value: '168小时'
  },
  {
    icon: 'Document',
    label: '总任务数',
    value: 42
  },
  {
    icon: 'CircleCheck',
    label: '平均完成率',
    value: '87%'
  }
])

// 周报记录
const weeklyRecords = ref([
  {
    id: 1,
    week: '2024年第10周',
    dateRange: '3/4 - 3/10',
    workHours: 40,
    taskCount: 5,
    completionRate: 100,
    tasks: [
      {
        title: '首页UI设计',
        description: '完成了应用首页的UI设计，包括布局优化和交互细节调整',
        hours: 12,
        priority: 'high',
        completed: true
      },
      {
        title: '用户认证模块',
        description: '实现了基于JWT的用户认证功能，包括登录、注册和找回密码',
        hours: 16,
        priority: 'high',
        completed: true
      },
      {
        title: '数据可视化组件',
        description: '开发了数据统计图表组件，支持多种展示方式',
        hours: 12,
        priority: 'medium',
        completed: true
      }
    ],
    plans: [
      '优化移动端适配',
      '实现消息推送功能',
      '编写用户使用文档'
    ],
    issues: '目前在IE浏览器上还存在一些兼容性问题，需要进一步处理。'
  },
  {
    id: 2,
    week: '2024年第9周',
    dateRange: '2/26 - 3/3',
    workHours: 42,
    taskCount: 4,
    completionRate: 75,
    tasks: [
      {
        title: '日程管理模块',
        description: '开发日程管理功能，支持添加、编辑和删除日程',
        hours: 14,
        priority: 'high',
        completed: true
      },
      {
        title: '接口文档',
        description: '编写API接口文档，包含接口定义、参数说明和返回值说明',
        hours: 8,
        priority: 'medium',
        completed: true
      },
      {
        title: '性能优化',
        description: '对系统进行性能分析和优化，重点解决页面加载速度问题',
        hours: 12,
        priority: 'high',
        completed: true
      },
      {
        title: '单元测试',
        description: '编写核心功能的单元测试用例',
        hours: 8,
        priority: 'medium',
        completed: false
      }
    ],
    plans: [
      '完成单元测试用例',
      '开始集成测试',
      '准备上线前的安全审查'
    ],
    issues: '测试团队资源紧张，可能需要开发团队协助完成部分测试工作。'
  },
  {
    id: 3,
    week: '2024年第8周',
    dateRange: '2/19 - 2/25',
    workHours: 38,
    taskCount: 3,
    completionRate: 67,
    tasks: [
      {
        title: '数据库优化',
        description: '优化数据库查询性能，添加索引，调整表结构',
        hours: 16,
        priority: 'high',
        completed: true
      },
      {
        title: '权限管理',
        description: '实现基于角色的权限控制系统',
        hours: 14,
        priority: 'high',
        completed: true
      },
      {
        title: '导出功能',
        description: '添加数据导出为Excel和PDF的功能',
        hours: 8,
        priority: 'medium',
        completed: false
      }
    ],
    plans: [
      '完成导出功能',
      '添加数据导入功能',
      '编写管理员使用手册'
    ],
    issues: '导出PDF时中文字体显示存在问题，正在寻找解决方案。'
  }
])

// 根据搜索关键词过滤周报记录
const filteredWeeklyRecords = computed(() => {
  if (!searchKeyword.value) return weeklyRecords.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return weeklyRecords.value.filter(record => {
    return record.week.toLowerCase().includes(keyword) ||
           record.tasks.some(task => 
             task.title.toLowerCase().includes(keyword) || 
             task.description.toLowerCase().includes(keyword)
           )
  })
})

// 初始化
onMounted(() => {
  fetchWeeklyStats()
  nextTick(() => {
    initCharts()
  })
})

// 初始化图表
const initCharts = () => {
  // 初始化工作时长趋势图
  if (workTrendChart.value) {
    workTrendChartInstance = echarts.init(workTrendChart.value)
    const workTrendOption = {
      title: {
        text: '工作时长趋势'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['第5周', '第6周', '第7周', '第8周', '第9周', '第10周']
      },
      yAxis: {
        type: 'value',
        name: '工时(小时)'
      },
      series: [
        {
          name: '工作时长',
          type: 'line',
          data: [35, 37, 42, 38, 42, 40],
          smooth: true,
          lineStyle: {
            color: '#1e5eff'
          },
          itemStyle: {
            color: '#1e5eff'
          }
        }
      ]
    }
    workTrendChartInstance.setOption(workTrendOption)
  }
  
  // 初始化任务完成情况图
  if (taskCompletionChart.value) {
    taskCompletionChartInstance = echarts.init(taskCompletionChart.value)
    const taskCompletionOption = {
      title: {
        text: '任务完成情况'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['已完成', '进行中', '未开始']
      },
      series: [
        {
          name: '任务状态',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 28, name: '已完成', itemStyle: { color: '#67C23A' } },
            { value: 10, name: '进行中', itemStyle: { color: '#1e5eff' } },
            { value: 4, name: '未开始', itemStyle: { color: '#909399' } }
          ]
        }
      ]
    }
    taskCompletionChartInstance.setOption(taskCompletionOption)
  }
  
  // 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', () => {
    workTrendChartInstance && workTrendChartInstance.resize()
    taskCompletionChartInstance && taskCompletionChartInstance.resize()
  })
}

// 更新工作趋势图表
const updateWorkTrendChart = () => {
  if (!workTrendChartInstance) return
  
  let xAxisData = []
  let seriesData = []
  
  if (workTrendType.value === 'week') {
    xAxisData = ['第5周', '第6周', '第7周', '第8周', '第9周', '第10周']
    seriesData = [35, 37, 42, 38, 42, 40]
  } else {
    xAxisData = ['1月', '2月', '3月']
    seriesData = [160, 152, 170]
  }
  
  workTrendChartInstance.setOption({
    xAxis: {
      data: xAxisData
    },
    series: [
      {
        data: seriesData
      }
    ]
  })
}

// 获取周报统计数据
const fetchWeeklyStats = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 更新统计数据
    overviewStats.value[0].value = weeklyRecords.value.length
    
    // 计算总工时
    const totalHours = weeklyRecords.value.reduce((sum, record) => sum + record.workHours, 0)
    overviewStats.value[1].value = `${totalHours}小时`
    
    // 计算总任务数
    const totalTasks = weeklyRecords.value.reduce((sum, record) => sum + record.taskCount, 0)
    overviewStats.value[2].value = totalTasks
    
    // 计算平均完成率
    const avgCompletionRate = weeklyRecords.value.reduce(
      (sum, record) => sum + record.completionRate, 0
    ) / weeklyRecords.value.length
    overviewStats.value[3].value = `${Math.round(avgCompletionRate)}%`
    
    totalRecords.value = weeklyRecords.value.length
    
    loading.value = false
    
    nextTick(() => {
      updateCharts()
    })
  }, 500)
}

// 更新图表数据
const updateCharts = () => {
  updateWorkTrendChart()
  
  // 在实际应用中，这里应该根据获取到的数据更新图表
}

// 查看周报详情
const viewWeeklyDetail = (weekly) => {
  currentWeekly.value = weekly
  detailDialogVisible.value = true
}

// 删除周报
const deleteWeekly = (weekly) => {
  ElMessageBox.confirm(
    `确定要删除"${weekly.week}"的周报记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    const index = weeklyRecords.value.findIndex(item => item.id === weekly.id)
    if (index !== -1) {
      weeklyRecords.value.splice(index, 1)
      ElMessage.success('删除成功')
      fetchWeeklyStats() // 重新加载统计数据
    }
  }).catch(() => {
    // 取消删除
  })
}

// 导出统计
const exportStats = () => {
  ElMessage.success('统计报告导出成功')
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  // 在实际应用中，这里应该重新加载数据
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const map = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return map[priority] || priority
}
</script>

<style scoped>
.weekly-stats-container {
  padding: 20px;
  background-color: #f9fbff;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-header h3 {
  font-size: 24px;
  color: #1e5eff;
  margin: 0;
}

.period-selector {
  display: flex;
  gap: 15px;
}

.stats-overview {
  margin-bottom: 25px;
}

.stat-card {
  height: 120px;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  background-color: rgba(30, 94, 255, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #1e5eff;
  margin-right: 15px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stats-charts {
  margin-bottom: 25px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 周报详情样式 */
.weekly-detail {
  padding: 0 10px;
}

.weekly-detail h4 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #1e5eff;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h5 {
  margin-bottom: 10px;
  color: #606266;
  font-size: 16px;
}

.task-list {
  padding-left: 0;
  list-style: none;
}

.task-item {
  background-color: #f9fbff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 10px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.task-title span {
  font-weight: bold;
}

.task-desc {
  color: #606266;
  margin-bottom: 8px;
  font-size: 14px;
}

.task-meta {
  display: flex;
  gap: 20px;
  color: #909399;
  font-size: 13px;
}

.plan-list {
  padding-left: 20px;
}

.plan-list li {
  margin-bottom: 5px;
}
</style> 